package com.wxd.controller;

import com.wxd.BookService;
import com.wxd.domain.Book;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/books")
public class BookController {
    @Autowired
    private BookService bookService;

    @PostMapping
    public Result save(@RequestBody Book book) {
        boolean flag = bookService.save(book);
        return new Result(flag ? Code.SAVE_OK : Code.SAVE_ERR, flag);
    }

    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id) {

        boolean flag = bookService.delete(id);
        return new Result(flag ? Code.DELETE_OK : Code.DELETE_ERR, flag);
    }

    @PutMapping
    public Result update(@RequestBody Book book) {
        boolean flag = bookService.update(book);
        return new Result(flag ? Code.UPDATE_OK : Code.UPDATE_ERR, flag);
    }

    @GetMapping("/{id}")
    public Result getById(@PathVariable Integer id) {
        Book book = bookService.getById(id);
        String msg = book != null ? "查询成功" : "查询失败";
        Integer code = book != null ? Code.SAVE_OK : Code.SAVE_ERR;
        return new Result(code, book, msg);
    }

    @GetMapping
    public Result getAllBooks() {
        System.out.println("getAllBooks-----");
        List<Book> allBooks = bookService.getAllBooks();
        String msg = allBooks != null ? "查询成功" : "查询失败";
        Integer code = allBooks != null ? Code.SAVE_OK : Code.SAVE_ERR;
        return new Result(code, allBooks, msg);
    }
}
